import {
  addAfterSalesNeedInfoEx,
  getDeviceDetailById,
  updateAfterSalesNeedInfoEx,
} from '@/services/sales/salesNeedInfo';
import { CloseCircleOutlined } from '@ant-design/icons';
import ProForm, { ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { FooterToolbar, PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Col, message, Popover, Row } from 'antd';

import type { ProFormInstance } from '@ant-design/pro-components';
import { Form } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useLocation, useModel } from 'umi';
import styles from './style.less';

import { EditableProTable } from '@ant-design/pro-table';

interface TableFormDateType {
  id: string;
  workId?: string;
  name?: string;
  department?: string;
  isNew?: boolean;
  editable?: boolean;
}
const fieldLabels = {
  name: '仓库名',
  url: '仓库域名',
  owner: '仓库管理员',
  approver: '审批人',
  dateRange: '生效日期',
  type: '仓库类型',
  name2: '任务名',
  url2: '任务描述',
  owner2: '执行人',
  approver2: '责任人',
  dateRange2: '生效日期',
  type2: '任务类型',
};
const tableData = [
  {
    key: '1',
    workId: '00001',
    name: 'John Brown',
    department: 'New York No. 1 Lake Park',
  },
  {
    key: '2',
    workId: '00002',
    name: 'Jim Green',
    department: 'London No. 1 Lake Park',
  },
  {
    key: '3',
    workId: '00003',
    name: 'Joe Black',
    department: 'Sidney No. 1 Lake Park',
  },
];

const DeviceInfoDetail: React.FC<{}> = () => {
  // const params = useParams();
  const location = useLocation();
  // console.log(params, '---ceshi---');
  console.log(location.query.id, '---ceshi1---');

  const [formTitle, setFormTitle] = useState('新建售后需求'); //

  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  // 表格数据
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);

  const [formDisabled, setFormDisabled] = useState(false); //设置表单禁用

  // 个人用户数据
  let user = {};
  let deviceInfo = {};

  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  console.log(currentUser, '---currentUser---');

  useEffect(() => {
    // Using an IIFE
    (async () => {
      // 相当于新建
      if (location.query.id !== undefined && location.query.id !== null) {
        const result = await getDeviceDetailById({ id: location.query.id });
        setFormDisabled(true);
        setDataSource(result?.data?.shaftInfoExList);
        user = result?.data?.userEx;
        deviceInfo = result?.data?.deviceInfoEx;
        formRef?.current?.setFieldsValue({
          userId: { label: user?.name, value: user?.id },
          licensOrderId: {
            label: result?.data?.licenseOrderNum,
            value: result?.data?.licenseOrderNum,
          },
          licenseCount: result?.data?.licenseCount,
          driveName: deviceInfo?.deviceName,
          vm: deviceInfo?.vm,
          isProduction: deviceInfo?.production,
          plcType: deviceInfo?.plcType,
        });
      }
    })();
  }, []);
  console.log(location.query.id, '--location.query.id---');
  const formAdd = location.query.id === null || location.query.id === undefined ? true : false;
  // setDataSource([{ id: '00111', identification: '12', motorOrderNum: 'weew' }]);

  /**
   * 穿梭框的数据设置
   */

  const formRef = useRef<
    ProFormInstance<{
      name: string;
      company?: string;
      useMode?: string;
    }>
  >();
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },

    {
      title: '轴名称', //表头显示的名称
      search: false,
      dataIndex: 'shaftName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 120,
    },

    {
      title: '硬件标识符', //表头显示的名称
      search: false,
      dataIndex: 'hardwareIdentifier', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 120,
      valueType: 'digit',
    },

    {
      title: '驱动类型', //
      search: false,
      key: 'driveType',
      dataIndex: 'driveType',
      valueType: 'select',
      valueEnum: {
        0: { text: 'V90', status: 'Default' },
        1: {
          text: 'S210',
          status: 'Error',
        },
      },
    },

    {
      title: '电机订货号', //
      search: false,
      dataIndex: 'motorOrderNum',
      width: 120,
    },

    {
      title: '电机ID', //表头显示的名称
      search: false,
      dataIndex: 'motorId', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      valueType: 'digit',
    },
    {
      title: '额定电流', //表头显示的名称
      search: false,
      dataIndex: 'ratedCurrent',
      valueType: 'digit',
    },
    {
      title: '额定扭矩', //表头显示的名称
      search: false,
      dataIndex: 'ratedTorque', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      valueType: 'digit',
    },
    {
      title: '额定功率', //表头显示的名称
      search: false,
      dataIndex: 'ratedPower',
      valueType: 'digit',
    },
    {
      title: '编码器', //表头显示的名称
      search: false,
      dataIndex: 'ecoderType', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      valueType: 'digit',
    },
    {
      title: '抱闸', //表头显示的名称
      search: false,
      dataIndex: 'brake',
      valueType: 'digit',
    },
    {
      title: '额定速度', //表头显示的名称
      search: false,
      dataIndex: 'ratedSpeed', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '额定电压', //表头显示的名称
      search: false,
      dataIndex: 'ratedVoltage',
    },
    {
      title: '电机惯量', //表头显示的名称
      search: false,
      dataIndex: 'motorInertia', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '机械结构', //表头显示的名称
      search: false,
      dataIndex: 'mechanicalStructure',
    },
    {
      title: '控制模式', //表头显示的名称
      search: false,
      dataIndex: 'controlMode', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },

    {
      title: '通讯报文', //表头显示的名称
      search: false,
      dataIndex: 'commTelegram',
    },

    {
      title: '附加报文', //表头显示的名称
      search: false,
      dataIndex: 'additionalTelegram', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '电机方向', //表头显示的名称
      search: false,
      dataIndex: 'motorRotation',
    },
    {
      title: '齿轮比负载(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'gearRationLoad', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '齿轮比电机(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'gearRationMotor',
    },

    {
      title: '定位精度(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'positionAccuracy', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '负载一圈的距离(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'loadOneTurnDistance',
    },
    {
      title: '软限位激活(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'softLimitActive', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '软限位(正)(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'softLimitPositive',
    },

    {
      title: '软限位(负)(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'softLimitNegative', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '0-Vmax时间(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'increaseTimeEpos',
    },
    {
      title: 'Vmax-0时间(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'decreaseTimeEpos', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '模态轴是否激活(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'modualActiveEpos',
    },

    {
      title: '模态长度(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'modualLengthEpos', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: 'DI1(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'di1Epos',
    },
    {
      title: 'DI2(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'di2Epos', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: 'DI3(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'di3Epos',
    },

    {
      title: 'DO1(V90 EPOS)', //表头显示的名称
      search: false,
      dataIndex: 'do1Epos', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '0-Vmax时间(V90TO/S210)', //表头显示的名称
      search: false,
      dataIndex: 'increaseTimeTO',
    },
    {
      title: 'Vmax-0时间(V90TO/S210)', //表头显示的名称
      search: false,
      dataIndex: 'decreaseTimeTO', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '0-nmax时间(V90Speed)', //表头显示的名称
      search: false,
      dataIndex: 'increaseTimeSpeed',
    },
    {
      title: 'nmax-0时间(V90Speed)', //表头显示的名称
      search: false,
      dataIndex: 'decreaseTimeSpeed',
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
        <EditableProTable.RecordCreator
          key="copy"
          record={{
            ...record,
            id: (Math.random() * 1000000).toFixed(0),
          }}
        >
          <a>复制</a>
        </EditableProTable.RecordCreator>,
      ],
    },
  ];

  const handleSubmit = async () => {
    if (formTitle == '新建售后需求') {
      await addAfterSalesNeedInfo(form.getFieldsValue());
    } else {
      await updateAfterSalesNeedInfo(form.getFieldsValue());
    }

    message.success('添加成功');
    setModalVisit(false);
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
  };
  const [error, setError] = useState<ErrorField[]>([]);
  const getErrorInfo = (errors: ErrorField[]) => {
    // return null;
    const errorCount = errors.filter((item) => item.errors.length > 0).length;

    if (!errors || errorCount === 0) {
      return null;
    }
    const scrollToField = (fieldKey: string) => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };
    const errorList = errors.map((err) => {
      if (!err || err.errors.length === 0) {
        return null;
      }
      const key = err.name[0] as string;
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <CloseCircleOutlined className={styles.errorIcon} />
          <div className={styles.errorMessage}>{err.errors[0]}</div>
          <div className={styles.errorField}>{fieldLabels[key]}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={(trigger: HTMLElement) => {
            if (trigger && trigger.parentNode) {
              return trigger.parentNode as HTMLElement;
            }
            return trigger;
          }}
        >
          <CloseCircleOutlined />
        </Popover>
        {errorCount}
      </span>
    );
  };

  const onFinish = async (values: Record<string, any>) => {
    // setError([]);
    console.log(values, dataSource, '---tijiao-1212121---');
    debugger;

    try {
      // 新增
      if (!formDisabled) {
        await addAfterSalesNeedInfoEx({
          userId: values.userId.value,
          driveName: values.driveName,
          isProduction: values.isProduction.value,
          plcType: values.plcType.value,
          vm: values.vm.value,
          licenseOrderNum: values.licensOrderId.label,
          licenseCount: values.licenseCount,
          shaftInfoExDtoList: dataSource.map((item) => {
            return {
              identification: item.identification,
              motorOrderNum: item.motorOrderNum,
              driveType: item.driveType,
              hardwareIdentifier: item.hardwareIdentifier,
              motorId: item.motorId,
              ratedCurrent: item.ratedCurrent,
              ratedTorque: item.ratedTorque,
              ratedPower: item.ratedPower,
              ecoderType: item.ecoderType,
              brake: item.brake,
              shaftName: item.shaftName,
            };
          }),
        });
      } else {
        // 更新
        await updateAfterSalesNeedInfoEx({
          id: location.query.id,
          userId: values.userId.value,
          driveName: values.driveName,
          isProduction: values.isProduction.value,
          plcType: values.plcType.value,
          vm: values.vm.value,
          licenseOrderNum: values.licensOrderId.label,
          licenseCount: values.licenseCount,
          shaftInfoExDtoList: dataSource.map((item) => {
            return {
              identification: item.identification,
              motorOrderNum: item.motorOrderNum,
              driveType: item.driveType,
              hardwareIdentifier: item.hardwareIdentifier,
              motorId: item.motorId,
              ratedCurrent: item.ratedCurrent,
              ratedTorque: item.ratedTorque,
              ratedPower: item.ratedPower,
              ecoderType: item.ecoderType,
              brake: item.brake,
              shaftName: item.shaftName,
            };
          }),
        });
      }

      message.success('提交成功');
    } catch {
      // console.log
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    setError(errorInfo.errorFields);
  };

  /**
   * 穿梭框的数据设置
   */

  return (
    <ProForm
      layout="vertical"
      hideRequiredMark
      submitter={{
        render: (props, dom) => {
          return (
            <FooterToolbar>
              {getErrorInfo(error)}
              {dom}
            </FooterToolbar>
          );
        },
      }}
      formRef={formRef}
      initialValues={{ members: tableData }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <PageHeaderWrapper title={false} breadcrumb={undefined}>
        <Card title="驱动参数列表" className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              {/* <ProFormSelect
                // options={[
                //   {
                //     value: 'chapter',
                //     label: '盖章后生效',
                //   },
                // ]}
                fieldProps={{
                  labelInValue: true,
                  //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                  onChange: (val, val2) => {
                    console.log(val, val2);
                  },
                }}
                initialValue={formAdd ? {} : { label: deviceInfo.deviceName, value: deviceInfo.id }}
                debounceTime={1000}
                name="deviceId"
                label="设备信息"
                showSearch
                request={async (para) => {
                  console.log(para, '--para-');
                  const result = await deviceList({ blurry: para.keyWords });
                  return result.data.map((item) => {
                    return { label: item.deviceName, value: item.id, object: item };
                  });
                }}
              /> */}

              <ProFormText
                label="设备名称"
                name="driveName"
                rules={[
                  {
                    required: true,
                    message: '请输入设备名称',
                  },
                ]}
                disabled={formDisabled}
                // rules={[{ required: true, message: '请选择' }]}
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <ProFormSelect
                // options={[
                //   {
                //     value: 'chapter',
                //     label: '盖章后生效',
                //   },
                // ]}
                fieldProps={{
                  //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                  onChange: (val, val2) => {
                    console.log(val, val2);
                  },
                }}
                initialValue={formAdd ? { label: '电子', value: 0 } : {}}
                name="vm"
                label="行业"
                options={[
                  { label: '电子', value: 0 },
                  { label: '机械', value: 1 },
                  { label: '其他', value: 2 },
                ]}
              />
            </Col>
            <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
              <ProFormSelect
                // options={[
                //   {
                //     value: 'chapter',
                //     label: '盖章后生效',
                //   },
                // ]}
                fieldProps={{
                  //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                  onChange: (val, val2) => {
                    console.log(val, val2);
                  },
                }}
                initialValue={formAdd ? { label: '是', value: 1 } : {}}
                name="isProduction"
                label="是否量产"
                options={[
                  { label: '是', value: 1 },
                  { label: '否', value: 0 },
                ]}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormSelect
                // options={[
                //   {
                //     value: 'chapter',
                //     label: '盖章后生效',
                //   },
                // ]}
                fieldProps={{
                  //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                  onChange: (val, val2) => {
                    console.log(val, val2);
                  },
                }}
                initialValue={formAdd ? { label: '1511T', value: '1' } : {}}
                name="plcType"
                label="PLC类型"
                options={[
                  { label: '1511T', value: '1' },
                  { label: '1214', value: '0' },
                ]}
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24} />
          </Row>
        </Card>

        <Card title="轴信息" className={styles.card} bordered={false}>
          <EditableProTable<TableFormDateType>
            value={dataSource}
            scroll={{ x: 4000 }}
            recordCreatorProps={{
              record: () => {
                return {
                  id: `0${Date.now()}`,
                };
              },
              newRecordType: 'dataSource',
            }}
            // request={async () => ({
            //   data: defaultData,
            //   total: 3,
            //   success: true,
            // })}
            onChange={setDataSource}
            columns={columns}
            rowKey="id"
          />
        </Card>
      </PageHeaderWrapper>
    </ProForm>
  );
};

export default DeviceInfoDetail;
